package com.xd.common.exception;

import com.github.pagehelper.Page;
import com.xd.core.system.vo.PageVo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;

@Data
@NoArgsConstructor
@SuperBuilder
@AllArgsConstructor
public class Result<T> {
    /*代码*/
    private int code;
    /*结果*/
    private T data;
    /*错误信息*/
    private String msg;
    /*分页-总量*/
    private long total;
    /*分页-当前页*/
    private long page;

    public Result(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public static Result success(Object data) {
        ResultBuilder builder = Result.builder();
        builder.code(200);
        builder.msg("操作成功");
        if (data instanceof Page) {
            builder.total(((Page) data).getTotal());
            builder.page(((Page) data).getPageNum());
            builder.data(((Page) data).getResult());
        } else if (data instanceof PageVo){
            builder.data(data);
            builder.total(((PageVo) data).getTotal());
            builder.page(((PageVo) data).getPageNum());
            builder.data(((PageVo) data).getList());

        }else{
            builder.data(data);
        }
        return builder.build();
    }

    public static Result error(String message, int code) {
        return Result.builder()
                .code(code)
                .msg(message)
                .build();
    }

    public static Result error(String message) {
        return Result.builder()
                .code(500)
                .msg(message)
                .build();
    }
}
